package structuralPatterns.proxy;

interface Subject {
    void request();
}

class RealSubject implements Subject {
    public void request() {
        System.out.println("RealSubject: Handling request.");
    }
}

class Proxy implements Subject {
    private RealSubject realSubject;

    public void request() {
        // 代理对象可以自定义逻辑，在执行真实对象request前后添加逻辑
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        if (checkAccess()) {
            realSubject.request();
            logAccess();
        }
    }

    private boolean checkAccess() {
        // Some real checks should go here.
        System.out.println("Proxy: Checking access prior to firing a real request.");
        return true;
    }

    private void logAccess() {
        System.out.println("Proxy: Logging the time of request.");
    }
}

public class ProxyPattern {
    public static void main(String[] args) {
        Subject subject = new Proxy();
        subject.request();
    }
}
